﻿using System;
using System.Collections.Generic;
using System.Text;
using AMS.DataAccess.Sql;
using System.IO;

namespace AMS.DataAccess
{
    /// <summary>
    /// 打印SQL语句到日志文件中的类
    /// </summary>
    public static class SqlDebugger
    {
        private static bool enableDebug = true;

        /// <summary>
        /// 获取或设置是否允许打印SQL语句，默认为 true
        /// </summary>
        public static bool EnableDebug
        {
            get { return enableDebug; }
            set { enableDebug = value; }
        }

        private static string logFilePath;

        /// <summary>
        /// 获取或设置日志文件的路径，默认为 ..\\log\\sql.log
        /// </summary>
        public static string LogFilePath
        {
            get { return logFilePath ?? "..\\log\\sql.log"; }
        }

        private static volatile object syncLock = new object();
        static StreamWriter writer;

        /// <summary>
        /// 将SQL语句输出到文件
        /// </summary>
        /// <param name="sql"></param>
        public static void WriteLine(SqlStatement sql)
        {
            if (EnableDebug)
            {
                AnsycWriteLine(sql.ToString());
            }
        }

        /// <summary>
        /// 将SQL语句输出到文件。此方法是线程安全的
        /// </summary>
        /// <param name="sql"></param>
        private static void AnsycWriteLine(string sql)
        {
            lock (syncLock)
            {
                if (writer == null)
                {
                    writer = new StreamWriter(LogFilePath, true, Encoding.Default);
                }

                // TODO: 暂时用相对路径
                writer.WriteLine(string.Format("[{0}]", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")));
                writer.WriteLine(sql);
                writer.Flush();
                writer.Close();
            }
        }
    }
}
